<template>
  <div class="divBox relative">
    <!-- 搜索栏 -->
    <el-card :bordered="false" shadow="never" class="ivu-mt" :body-style="{ padding: 0 }">
      <div class="padding-add">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
          <el-form-item label="仓库名称" prop="warehouseName">
            <el-input
              v-model="queryParams.warehouseName"
              placeholder="请输入仓库名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="仓库分类" prop="warehouseType">
            <el-select v-model="queryParams.warehouseType" placeholder="请选择仓库分类" clearable>
              <el-option label="总仓" :value="1" />
              <el-option label="城市仓" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="仓库城市" prop="warehouseCity">
            <el-cascader
              v-model="queryParams.citys"
              :options="regionData"
              :props="{ expandTrigger: 'hover', checkStrictly: true }"
              placeholder="请选择仓库城市"
              clearable
              style="width: 180px"
            />
          </el-form-item>
          <el-form-item label="仓库状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择仓库状态" clearable>
              <el-option label="启用" :value="1" />
              <el-option label="禁用" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <!-- 表格和操作栏 -->
    <el-card class="box-card mt14" :body-style="{ padding: '20px 20px' }" shadow="never" :bordered="false">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增仓库</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="loading" :data="warehouseList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="warehouseNumber" />
        <el-table-column label="仓库名称" align="center" prop="warehouseName">
          <template slot-scope="scope">
            {{ scope.row.warehouseName }}
            <el-tag v-if="scope.row.isDefault === 1" type="info" size="mini" style="margin-left: 4px;">默认</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="分类" align="center" prop="warehouseType">
          <template slot-scope="scope">
            {{ warehouseTypeText(scope.row.warehouseType) }}
          </template>
        </el-table-column>
        <el-table-column label="仓库城市" align="center" prop="warehouseCity" />
        <el-table-column label="备注" align="center" prop="remarks" />
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.limit"
        @size-change="limitChange"
        @current-change="paginationChange"
      />
    </el-card>
    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="form.warehouseName" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item label="仓库类型" prop="warehouseType">
          <el-select v-model="form.warehouseType" placeholder="请选择仓库类型" style="width: 100%">
            <el-option label="总仓" :value="1" />
            <el-option label="城市仓" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="上级仓库" prop="pid">
          <!-- <el-input v-model="form.pid" placeholder="请输入仓库编码" />
           -->
           <el-select v-model="form.pid" placeholder="请选择上级仓库" style="width: 100%">
            <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库编号" prop="warehouseNumber">
          <el-input v-model="form.warehouseNumber" placeholder="请输入仓库编号" />
        </el-form-item>
        <el-form-item label="仓库城市" prop="citys">
          <el-cascader
            v-model="form.citys"
            :options="regionData"
            :props="{ expandTrigger: 'hover', checkStrictly: true }"
            placeholder="请选择仓库城市"
            clearable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="地图位置" prop="mapLocation">
          <el-input v-model="form.mapLocation" placeholder="请输入地图位置" style="width: 70%" />
          <el-button @click="showMapDialog = true" style="margin-left: 8px">选择位置</el-button>
        </el-form-item>
        <el-form-item label="详细地址" prop="detailedAddress">
          <el-input v-model="form.detailedAddress" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="仓库状态" prop="status">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" active-text="启用" inactive-text="禁用" />
        </el-form-item>
        <el-form-item label="备注说明" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注说明" />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="form.isDefault" :true-label="1" :false-label="0">默认仓库</el-checkbox>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </div>
    </el-dialog>
    <MapDialog v-model="showMapDialog" :position="form.mapLocation" @select="onMapSelect" v-if="showMapDialog" />
  </div>
</template>

<script>
import { listWarehouse, addWarehouse, updateWarehouse, delWarehouse } from '@/api/delivery';
import { regionData } from 'element-china-area-data';
import MapDialog from '@/components/MapDialog.vue';
import { listStore } from '@/api/commercial';

export default {
  name: 'Warehouse',
  components: { MapDialog },
  data() {
    return {
      loading: false,
      showSearch: true,
      total: 0,
      warehouseList: [],
      title: '',
      open: false,
      regionData: regionData,
      ids: [],
      single: true,
      multiple: true,
      queryParams: {
        page: 1,
        limit: 10,
        warehouseName: '',
        warehouseType: undefined,
        citys: [],
        warehouseCity: '',
        status: undefined,
      },
      form: {
        id: null,
        warehouseName: '',
        warehouseType: undefined,
        warehouseNumber: '',
        citys: [],
        warehouseCity: '',
        mapLocation: '',
        detailedAddress: '',
        status: 1,
        remarks: '',
        isDefault: 0,
        phone: '',
        password: '',
      },
      rules: {
        warehouseName: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }],
        warehouseType: [{ required: true, message: '请选择仓库类型', trigger: 'change' }],
        warehouseNumber: [{ required: true, message: '请输入仓库编号', trigger: 'blur' }],
        citys: [{ required: true, message: '请选择仓库城市', trigger: 'change' }],
        mapLocation: [{ required: true, message: '请输入地图位置', trigger: 'blur' }],
        detailedAddress: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
        status: [{ required: true, message: '请选择仓库状态', trigger: 'change' }],
        phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      },
      showMapDialog: false,
      storeList: [],
    };
  },
  created() {
    this.getList();
    this.getStoreList();
  },
  methods: {
    getStoreList() {
      listStore({ type: 1, page: 1, limit: 999 }).then((res) => {
        this.storeList = res.list.filter(item => item.warehouseType == 1);
      });
    },
    warehouseTypeText(type) {
      if (type === 1) return '总仓';
      if (type === 2) return '城市仓';
      return '-';
    },
    limitChange(limit) {
      this.queryParams.limit = limit;
      this.getList();
    },
    paginationChange(page) {
      this.queryParams.page = page;
      this.getList();
    },
    getList() {
      this.loading = true;
      // 处理城市筛选
     if (this.queryParams.citys && this.queryParams.citys.length > 0) {
          let currentNode = this.regionData;
          let lastLabel = '';
          for (const value of this.queryParams.citys) {
            const found = currentNode.find(item => item.value === value);
            if (found) {
              lastLabel = found.label;
              currentNode = found.children || [];
            }
          }
          this.queryParams.warehouseCity = lastLabel;
          // delete this.queryParams.citys
        } else {
          this.queryParams.warehouseCity = '';
        }
      console.log(this.queryParams,222);
      const params = JSON.parse(JSON.stringify(this.queryParams));
      delete params.citys;
      listWarehouse(params).then(res => {
        this.warehouseList = res.list || [];
        this.total = res.total || 0;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.queryParams.citys = [];
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '新增仓库';
    },
    handleUpdate(row) {
      this.reset();
      this.open = true;
      this.title = '编辑仓库';
      console.log(row,252);
      // 回显数据
      Object.assign(this.form, row);
      // 处理城市回显
     const findCityPath = (data, targetCity) => {
          for (let item of data) {
            if (item.label === targetCity) {
              return [item.value];
            }
            if (item.children) {
              const path = findCityPath(item.children, targetCity);
              if (path) {
                return [item.value, ...path];
              }
            }
          }
          return null;
        };

        if (row.warehouseCity) {
          const cityPath = findCityPath(this.regionData, row.warehouseCity);
          if (cityPath) {
            this.form.citys = cityPath;
          }
        }

      // if (row.warehouseCity) {
      //   this.form.citys = row.warehouseCity.split('/');
      // }
    },
    handleDelete(row) {
      this.$confirm('确定要删除该仓库吗？', '提示', {
        type: 'warning'
      }).then(() => {
        delWarehouse(row.id).then(() => {
          this.$message.success('删除成功');
          this.getList();
        });
      });
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) return;
        // 处理城市字段，取 citys 最后一级 label
        if (this.form.citys && this.form.citys.length > 0) {
          let currentNode = this.regionData;
          let lastLabel = '';
          for (const value of this.form.citys) {
            const found = currentNode.find(item => item.value === value);
            if (found) {
              lastLabel = found.label;
              currentNode = found.children || [];
            }
          }
          this.form.warehouseCity = lastLabel;
        } else {
          this.form.warehouseCity = '';
        }
        const isEdit = !!this.form.id;
        const api = isEdit ? updateWarehouse : addWarehouse;
        api(this.form).then(() => {
          this.$message.success(isEdit ? '编辑成功' : '新增成功');
          this.open = false;
          this.getList();
        });
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        warehouseName: '',
        warehouseType: undefined,
        warehouseNumber: '',
        citys: [],
        warehouseCity: '',
        mapLocation: '',
        detailedAddress: '',
        status: 1,
        remarks: '',
        isDefault: 0,
        phone: '',
        password: '',
      };
      this.$refs.form && this.$refs.form.resetFields();
    },
    onMapSelect(lnglat, address) {
      this.form.mapLocation = lnglat;
      this.form.detailedAddress = address;
    },
  }
}
</script>

<style scoped>
.divBox { background: #fff; min-height: 100vh; }
.padding-add { padding: 18px 18px 0 18px; }
.mt14 { margin-top: 14px; }
.mb8 { margin-bottom: 8px; }
.el-form-item .el-input,
.el-form-item .el-select,
.el-form-item .el-cascader,
.el-form-item .el-switch,
.el-form-item .el-checkbox {
  width: 100%;
}
</style>